<template>
  <div class="app-container">
    <div class="search_container_warp">
      <el-form
        ref="queryFormRef"
        class="search_container"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item prop="nickname" label="姓名/账号">
          <el-input
            v-model="queryParams.nickname"
            clearable
            @keyup.enter="query"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query"
            ><i-ep-search />搜索</el-button
          >
          <el-button type="primary" @click="openDialog">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        class="customTableClass"
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
      >
        <el-table-column label="序号" type="index" align="center" width="60" />
        <el-table-column label="姓名" prop="nickname" min-width="120" />
        <el-table-column
          label="账号"
          prop="username"
          align="center"
          min-width="100"
        />
        <el-table-column
          label="手机号码"
          prop="phone"
          align="center"
          width="120"
        />
        <el-table-column
          label="状态"
          prop="statusName"
          align="center"
          width="100"
        />
        <el-table-column label="操作" prop="code" align="center" width="120">
          <template #default="scope">
            <el-icon :size="16" class="editIconClass">
              <Edit @click="editFn(scope.row)" />
            </el-icon>
            <el-icon :size="16" class="deleteIconClass">
              <i-ep-delete @click="handleDelete(scope.row.id)" />
            </el-icon>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 修改状态弹窗 -->
    <el-dialog
      modal-class="userDialogClass"
      v-if="dialog.visible"
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      draggable
      align-center
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="" />
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="formData.username"
            placeholder=""
            autocomplete="off"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder=""
            autocomplete="new-password"
            show-password
          />
          <span class="passTipsClass">
            密码规则:8-16位至少两种字
            符(大写字母、小写字母、数字、特殊字符)组合</span
          >
        </el-form-item>
        <el-form-item label="确定密码" prop="passwordCheck">
          <el-input
            v-model="formData.passwordCheck"
            type="password"
            placeholder=""
            autocomplete="new-password"
            show-password
          />
        </el-form-item>
				<el-form-item label="手机" prop="phone">
				  <el-input
				    v-model="formData.phone"
				    placeholder=""
				    autocomplete="new-password"
				  />
				</el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="item in statusOptions"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getUserPage,
  userCreate,
  userUpdate,
  userDelete,
} from "@/api/userManagement";
import { ItemPageVO, Options } from "@/api/userManagement/types";
import { queryFilter, computeHeiht, moreQueryFilter } from "@/utils/index";
const router = useRouter();

defineOptions({
  name: "UserManagement",
  inheritAttrs: false,
});
const queryFormRef = ref(ElForm);
const formRef = ref(ElForm);
const dataList = ref<ItemPageVO[]>([]);
const originaldataList = ref<ItemPageVO[]>([]);
const formData = reactive<ItemPageVO>({
  password: "",
  passwordCheck: "",
});
const loading = ref(false);
const statusOptions = ref<Options[]>([]);
const queryParams = reactive<ItemPageVO>({});

function validatePassword(password: string) {
  // const regex = new RegExp(
  //   "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,16}$"
  // );
  const regex = new RegExp("^(?=.*[a-z])(?=.*[A-Z]).{8,16}$");
  const regex2 = new RegExp("^(?=.*[a-zA-Z])(?=.*[0-9]).{8,16}$");
  const regex3 = new RegExp("^(?=.*[0-9a-zA-Z])(?=.*[!@#$%^&*]).{8,16}$");
  return regex.test(password) || regex2.test(password) || regex3.test(password);
  // return regex.test(password);
}
const validatePass = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("Please input the password"));
  } else {
    if (!validatePassword(value)) {
      callback(new Error(" "));
      return;
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("Please input the password again"));
  } else if (value !== formData.password) {
    callback(new Error("Two inputs don't match!"));
  } else {
    callback();
  }
};

const rules = reactive({
  nickname: [{ required: true, message: " ", trigger: "change" }],
  username: [{ required: true, message: " ", trigger: "change" }],
  phone: [{ required: false, message: " ", trigger: "change" }],
  status: [{ required: true, message: " ", trigger: "change" }],
  password: [
    { validator: validatePass, required: true, message: " ", trigger: "blur" },
  ],
  passwordCheck: [
    { validator: validatePass2, required: true, message: " ", trigger: "blur" },
  ],
});

statusOptions.value = [
  {
    label: "启用",
    value: 0,
  },
  {
    label: "停用",
    value: 1,
  },
];

const dialog = reactive({
  title: "新增用户",
  visible: false,
});

/** 查询 */
function query() {
  let { nickname } = queryParams;
  let arr: Options[] = [
    { label: "nickname", value: nickname },
    { label: "username", value: nickname },
  ];
  if (nickname) {
    dataList.value = moreQueryFilter(originaldataList.value, arr);
  } else {
    handleQuery();
  }
}

/** 查询 */
function handleQuery() {
  loading.value = true;
  getUserPage()
    .then(({ data }) => {
      data.forEach((v) => {
        v.statusName = statusOptions.value.find(
          (j) => j.value === v.status
        )?.label;
      });
      dataList.value = data;
      originaldataList.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

function openDialog() {
  dialog.title = "新增用户";
  dialog.visible = true;
  formData.id = undefined;
  formData.username = undefined;
  formData.nickname = undefined;
  formData.phone = undefined;
  formData.password = undefined;
  formData.passwordCheck = undefined;
  formData.status = 0;
}
/** open表单弹窗 */
function editFn(data: ItemPageVO) {
  dialog.title = "编辑用户";
  dialog.visible = true;
  formData.id = data.id;
  formData.username = data.username;
  formData.nickname = data.nickname;
  formData.phone = data.phone;
  formData.status = data.status;
  formData.password = undefined;
  formData.passwordCheck = undefined;
}

/** 删除赛队人员 */
function handleDelete(id?: any) {
  ElMessageBox.confirm("确认删除数据项?", "确认删除", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "error",
  }).then(() => {
    loading.value = true;
    userDelete(id)
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

function handleSubmit() {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const obj = Object.assign({}, formData);
      delete obj.passwordCheck;
      if (obj.id) {
        userUpdate(obj).then((res) => {
          ElMessage.success("修改成功");
          dialog.visible = false;
          handleQuery();
        });
      } else {
        userCreate(obj).then((res) => {
          ElMessage.success("新增成功");
          dialog.visible = false;
          handleQuery();
        });
      }
    }
  });
}
function closeDialog() {
  dialog.visible = false;
}

onMounted(() => {
  handleQuery();
  computeHeiht();
});
</script>
<style lang="scss" scoped>
:deep(.userDialogClass .el-dialog .el-form-item__content) {
  width: 50%;
}
.passTipsClass {
  position: absolute;
  width: 180px;
  line-height: 20px;
  right: -190px;
}
.passTipsClass:before {
  color: #f56c6c;
  content: "*";
}
</style>
